import JWT from "jsonwebtoken"
/**
 * @Author HuiLY
 * @Date 2023-03-08 21:18:47
 * @param {String} tokens
 * @returns {Promise<{status:boolean,payload:JWT.JwtPayload}>}
 * @ token验证
 */
function CheckToken(token) {
    // 为了简单起见，使用 huily 作为加密
    return new Promise((resolve, reject) => {
        JWT.verify(token, 'huily', (error, payload) => {
            if (error) {
                resolve({ status: false, error });
            } else {
                TokenInfo = payload
                resolve({ status: true, payload });
            }
        })
    })
}
/**
 * @Author HuiLY
 * @Date 2023-03-14 16:24:21
 * @param {number} expiresIn s
 * @returns Token
 */
function CreateToken(expiresIn = 60 * 60 * 24) {
    return new Promise((resolve, reject) => {
        resolve(JWT.sign({
            user: 'huily'
        }, 'huily', {
            expiresIn: expiresIn,
            issuer: 'huily'
        }))
    })
}

/**
 * @type JWT.JwtPayload
 */
let TokenInfo = null
/**
 * 
 * @returns {JWT.JwtPayload}
 */
function GetTokenInfo() {
    if (TokenInfo === null)
        throw new TypeError('token元数据为空!')
    return TokenInfo
}


export {
    CheckToken,
    CreateToken,
    GetTokenInfo
}